package com.authine.cloudpivot.ext.domain.impl;

import com.alibaba.cola.dto.RequestContext;
import com.alibaba.cola.dto.SingleResponse;
import com.alibaba.fastjson.JSONObject;
import com.authine.cloudpivot.ext.conf.ApplicationConf;
import com.authine.cloudpivot.ext.constants.PlatformConst;
import com.authine.cloudpivot.ext.util.BoServiceUtils;
import com.authine.cloudpivot.ext.util.PmUtil;
import com.authine.cloudpivot.ext.utils.kingdee.DateUtils;
import com.authine.mvp.app.launcher.dto.bo.query.expression.*;
import com.authine.mvp.app.launcher.dto.bo.response.BO;
import com.authine.mvp.app.launcher.dto.bo.response.BOList;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @program: gomro
 * @description:
 * @author: wlw
 * @create: 2021-10-18 19:58
 **/
@Slf4j
public class HandleExpireGoodsTask implements Runnable {
    @Override
    public void run() {
        log.info("=================HandleExpireGoods start=======================");
        try {
            // 设置登录信息，避免报错
            RequestContext.get().setCorpLoginId(PlatformConst.corpLoginId);
            RequestContext.get().setLoginId(PlatformConst.loginId);
            RequestContext.get().setLoginName(PlatformConst.loginName);
            log.info("RequestContext：{}", JSONObject.toJSONString(RequestContext.get()));

            ComplexCondition condition = new ComplexCondition();
            condition.setNature(Nature.AND);
            condition.getConditions().add(new SimpleCondition("saled", Operator.EQ, 1));
            condition.getConditions().add(new SimpleCondition("expiry", Operator.LTE, PmUtil.getEndDateStr(Calendar.DATE, 0)));
            SingleResponse<BOList> response = BoServiceUtils.findListByCondition(ApplicationConf.GOODES, condition);
            if (response.isSuccess()) {
                if (CollectionUtils.isEmpty(response.getData().getData())) {
                    log.error("此次未查询到过期商品");
                    return;
                }
                List<Map<String, Object>> maps = response.getData().getData().stream().map(m -> {
                    Map<String, Object> map = Maps.newHashMap();
                    map.put("id", m.get("id"));
                    map.put("saled", 0);
                    return map;
                }).collect(Collectors.toList());
                SingleResponse<BO> singleResponse = BoServiceUtils.batchUpdateBo(ApplicationConf.GOODES, maps);
                log.info("此次处理过期商品结果：{}",singleResponse.isSuccess());

            }
        } catch (Exception e) {
            log.error("HandleExpireGoods exception:",e);
        }
    }
}
